﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace DM4Script
{
    //public delegate void FormRunTask(Prototypes.ScriptTask task);

    public partial class ScriptParse
    {
        //public event FormRunTask evntFormRunTask;

        //variable in constructor
        /// <summary>
        /// Id table [run_script_header]
        /// </summary>
        public long RshId { set; get; }

        //variable in constructor
        /// <summary>
        /// text script for analize and execute
        /// </summary>
        public string ScriptTxt { set; get; }

        //variable in constructor
        /// <summary>
        /// name script 
        /// </summary>
        public string ScriptName { set; get; }

        /// <summary>
        /// status parses script
        /// </summary>
        private bool ErrorParse { get; set; }

        /// <summary>
        /// log result after analizes
        /// </summary>
        public List<Prototypes.Log> Logs = new List<Prototypes.Log>();

        private void LogAdd(string message)
        {
            Logs.Add(new Prototypes.Log(message));
        }

        /// <summary>
        /// declare section
        /// </summary>
        public Prototypes.DeclareSection Declare;
        /// <summary>
        /// run section
        /// </summary>
        public Prototypes.RunSection RunSection;


        /////////public static IDM4 Dm4Srv;


        /// <summary>
        /// analizes script
        /// </summary>
        /// <returns></returns>
        public bool Analize(string scriptTxt = null)
        {
            ErrorParse = false;

            if (!String.IsNullOrEmpty(scriptTxt)) ScriptTxt = scriptTxt;

            if (!String.IsNullOrEmpty(ScriptTxt))
            {
                GetNextToken();

                if (_curTok != (char) Token.Declare || !HandleDeclare())
                    Logs.Add(new Prototypes.Log(true, "Expected word 'DECLARE' or error in prototype"));
                else if (_curTok != (char) Token.Run || !HandleRun())
                    Logs.Add(new Prototypes.Log(true, "Expected word 'RUN' or error in prototype"));
                else if (_curTok != (char) Token.Eof)
                    Logs.Add(new Prototypes.Log(true, "Expected token EOF"));

                ErrorParse = Logs.Any(input => input.Error);
            }
            else
                Logs.Add(new Prototypes.Log(true, "Text script not found"));

            return !ErrorParse;
        }

        /// <summary>
        /// return error after analize
        /// </summary>
        /// <returns></returns>
        public string GetError()
        {
            return String.Join(System.Environment.NewLine, from err in Logs where err.Error select err.Message());
        }
    }
}